import {createElement} from "../utils/element";
import Cat2DocButton from "./button";

class Cat2DocPopover {
    #hostElement = null;
    #popover = null;
    #id = null;
    #mouseMove = this.#handleMouseMove.bind(this);
    constructor(hostElement, options) {
        this.#hostElement = hostElement;
        this.#popover = createPopover();
        this.#popover.setAttribute('id', this.#id);
        this.#popover.innerHTML = null;
        createPopoverContent(this.#popover, options);
        this.show();
    }
    get id() {
        return this.#id;
    }
    destory() {
        this.#popover.remove();
        this.#removeMouseMoveEvents();
    }
    show() {
        this.#popover.style.display='inline-flex'
        this.#resetPos();
        window.addEventListener('mousemove', this.#mouseMove);
    }
    hide() {
        this.#removeMouseMoveEvents();
        this.#popover.style.display='none'
    }
    #resetPos() {
        const rect = this.#hostElement.getBoundingClientRect();
        this.#popover.style.left= rect.left + rect.width/2 - this.#popover.offsetWidth/2 + 'px';
        this.#popover.style.top= rect.top - this.#popover.offsetHeight - 10 + 'px';
    }
    /** 移除鼠标移动事件 */
    #removeMouseMoveEvents() {
        if(this.#mouseMove) window.removeEventListener('mousemove', this.#mouseMove);
    }
    /** 处理鼠标移动事件 */
    #handleMouseMove(event) {
        const parentRect = this.#hostElement.getBoundingClientRect();
        const popoverRect = this.#popover.getBoundingClientRect();
        if(!Cat2DocPopover.#isRect(event, parentRect, 20) && !Cat2DocPopover.#isRect(event, popoverRect, 0)) {
            this.hide();
        }
    }
    /** 是否在指定区域内 */
    static #isRect(event, rect, extendWidth) {
        let x = event.clientX;
        let y = event.clientY;
        return x>=rect.left - extendWidth && x<rect.left+rect.width+extendWidth && y>=rect.top-extendWidth && y<rect.top+rect.height+extendWidth;
    }
}

function createPopoverContent(popoverElement, options) {
    if(options && options.rows) {
        options.rows.forEach(r=>{
            const row = createRow(popoverElement);
            if(r.buttons) {
                r.buttons.forEach(b=>{
                    new Cat2DocButton(row, b);
                })
            }
        });
    }
}

function createPopover() {
    const div = createElement('div', document.body, {
        className: 'c2d-popover',
        attr: {
            popover: 'auto'
        },
        style: {
            margin: '0px',
            position: 'absolute',
            display: 'none',
            flexDirection: 'column',
            minWidth: '20px',
            minHeight: '20px',
            zIndex: 999,
        }
    });
    return div;
}

function createRow(parentElement) {
    const row = createElement('div', parentElement, {});
    return row;
}

export default Cat2DocPopover
